package com.wys.spring;

import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicBoolean;

public class SpringApplicationStartListener implements SpringApplicationRunListener {

    private final static Logger logger = LoggerFactory.getLogger(SpringApplicationStartListener.class);

    AtomicBoolean start = new AtomicBoolean(false);

    public SpringApplicationStartListener(SpringApplication application, String[] args) {
        application.setAdditionalProfiles("base");
    }

    @SneakyThrows
    public void contextPrepared(ConfigurableApplicationContext context) {
    }

    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        environment.setDefaultProfiles("base");
    }

    @SneakyThrows
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        if (start.compareAndSet(false, true) && timeTaken.getSeconds() > 3) {
            ApplicationContextHolder.tryStartup();
            logger.warn("SpringBoot程序启动完成总耗时:{}秒，开始运行😊😊😊😊😁", timeTaken.getSeconds());
        }
        if (!ApplicationContextHolder.isStartup()) {
            logger.warn("SpringBoot程序开始启动😁😁😁😁😁");
        }
    }


    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        logger.error("SpringBoot程序启动失败😭😭😭😭😭:", exception);
        context.close();
    }


}
